package servlet;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Answer;
import model.Study;
import model.UserDetail;
import DAO.AnswerDao;
import DAO.StudyDao;
import DAO.StudyFineDao;
import DAO.UserDao;
import DAO.UserDetailDao;

public class AnswerNewAction implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		 
		 HttpSession session=request.getSession();
		 ActionForward forward=new ActionForward();
			
			int studyId = request.getParameter("studyId") != null
					&& request.getParameter("studyId") != "" ? Integer
					.parseInt(request.getParameter("studyId")) : 0;
			int userId = session.getAttribute("userid") != null
					&& session.getAttribute("userid") != "" ? Integer
					.parseInt((String)session.getAttribute("userid")) : 0;
			int questId = request.getParameter("questId") != null
							&& request.getParameter("questId") != "" ? Integer
							.parseInt(request.getParameter("questId")) : 0;
			
							
	

			if (userId < 1) {
				session.invalidate();
				Util.ShowError(response, "로그인해주세요");
			}
			if (studyId < 1 || questId < 1) {
				Util.ShowError(response, "잘못 된 접근입니다");
			}
			
			String content = request.getParameter("content") != null
					&& request.getParameter("content") != "" ? request.getParameter("content") : null;
			
			
		
			if(content==null)
			{
				Util.ShowError(response, "내용을 입력해주세요");
			}
			
			AnswerDao answerDao = new AnswerDao();
			Answer answer = new Answer();
			

			content=Util.toUTF8(content);
			
			answer=answerDao.getAnswerByUserId(questId, userId);
			
			answer.setContent(content);
			answer.setUid(userId);
			answer.setQid(questId);
			
			UserDetailDao userDetailDao = new UserDetailDao();
			StudyFineDao studyFineDao = new StudyFineDao();
			
			
			answerDao.updateAnswerInfo(answer);
			userDetailDao.updateClearQuest(userId);
			studyFineDao.updateConductQuest(studyId, userId);
			
		
			
			forward.setPath("./List.Quest");
			return forward;
			
		
	}

}
